

#include "session.h"
#include <algorithm>
#include <boost/asio/buffer.hpp>
#include <boost/system/detail/error_code.hpp>
#include <cstddef>
#include <cstdio>
#include "http_server.h"

Session::Session(io_context & io_context, HttpServer * http_server, ip::tcp::socket & socket, int64_t id):m_context(io_context),m_socket(std::move(socket))
{

	m_http_server = http_server;
	m_id = id;
}

void Session::StartSession()
{
	m_socket.async_read_some(boost::asio::buffer(m_read_buffer, m_read_buffer.size() - 1), [this](boost::system::error_code ec, std::size_t size){

		if (ec)
		{
			printf("[%s][%d:%s].\n", __func__, ec.value(), ec.message().c_str());
			CloseSocket();
		}
		else
		{
			m_read_buffer[size] = '\0';
			if (!m_data_buffer.empty() && *m_data_buffer.rbegin() == '\0')
			{
				m_data_buffer.erase(m_data_buffer.begin() + m_data_buffer.size() - 1);
			}
			for (std::size_t index = 0; index <= size; index++)
			{
				m_data_buffer.push_back(m_read_buffer[index]);
			}
			ProcessRequestData();
			StartSession();
		}
	});
}

void Session::ProcessRequestData()
{

}

void Session::CloseSocket()
{
	boost::system::error_code ec;
	m_socket.close(ec);
	m_http_server->RemoveSession(m_id);
	m_id = 0;
}



